const Job = require('../models/job');
const Company = require('../models/company');
const { Op } = require('sequelize');
const { calculatePagination } = require('../utils/pagination');

// 获取所有职位（支持分页和筛选）
exports.getAllJobs = async (req, res) => {
  try {
    const { page = 1, limit = 10, industry, location, experience, education, salaryRange } = req.query;
    const { offset, limit: limitNum } = calculatePagination(page, limit);
    const whereClause = {};

    // 构建筛选条件
    if (industry) whereClause.industry = { [Op.like]: `%${industry}%` };
    if (location) whereClause.location = { [Op.like]: `%${location}%` };
    if (experience) whereClause.experience = { [Op.like]: `%${experience}%` };
    if (education) whereClause.education = { [Op.like]: `%${education}%` };
    if (salaryRange) whereClause.salaryRange = { [Op.like]: `%${salaryRange}%` };

    // 仅显示活跃职位
    whereClause.status = 'active';

    const { count, rows: jobs } = await Job.findAndCountAll({
      where: whereClause,
      limit: limitNum,
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']],
      include: ['company'] // 关联查询公司信息
    });

    res.status(200).json({
      success: true,
      data: {
        jobs,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: limitNum,
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取职位列表失败',
      error: error.message
    });
  }
};

// 根据ID获取职位详情
exports.getJobById = async (req, res) => {
  try {
    const { id } = req.params;
    const job = await Job.findByPk(id, {
      include: ['company']
    });

    if (!job) {
      return res.status(404).json({
        success: false,
        message: '职位不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: job
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取职位详情失败',
      error: error.message
    });
  }
};

// 搜索职位（多条件组合查询）
exports.searchJobs = async (req, res) => {
  try {
    const {
      keyword,
      company,
      salaryMin,
      salaryMax,
      location,
      industry,
      experience,
      education,
      page = 1,
      limit = 10
    } = req.query;
    const { offset, limit: limitNum } = calculatePagination(page, limit);

    // 构建职位表的where条件
    const whereClause = { status: 'active' };
    if (keyword) {
      whereClause[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } },
        { requirements: { [Op.like]: `%${keyword}%` } },
        { industry: { [Op.like]: `%${keyword}%` } },
        { location: { [Op.like]: `%${keyword}%` } }
      ];
    }
    if (location) whereClause.location = { [Op.like]: `%${location}%` };
    if (industry) whereClause.industry = { [Op.like]: `%${industry}%` };
    if (experience) whereClause.experience = { [Op.like]: `%${experience}%` };
    if (education) whereClause.education = { [Op.like]: `%${education}%` };
    if (salaryMin || salaryMax) {
      // 假设salaryRange字段格式为"5000-8000"，可根据实际情况调整
      whereClause.salaryRange = {};
      if (salaryMin) whereClause.salaryRange[Op.gte] = salaryMin;
      if (salaryMax) whereClause.salaryRange[Op.lte] = salaryMax;
    }

    // 构建公司名的where条件
    let companyWhere = undefined;
    if (company) {
      companyWhere = { name: { [Op.like]: `%${company}%` } };
    }

    const { count, rows: jobs } = await Job.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']],
      include: [
        {
          association: 'company',
          where: companyWhere,
          required: !!company // 只有传company时才内连接
        }
      ]
    });

    res.status(200).json({
      success: true,
      data: {
        jobs,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '搜索职位失败',
      error: error.message
    });
  }
};

// 获取企业发布的所有职位
exports.getCompanyJobs = async (req, res) => {
  try {
    const company = await Company.findOne({
      where: { userId: req.user.id }
    });

    if (!company) {
      return res.status(404).json({
        success: false,
        message: '企业信息不存在'
      });
    }

    const jobs = await Job.findAll({
      where: { companyId: company.id },
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      success: true,
      data: jobs
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取企业职位列表失败',
      error: error.message
    });
  }
};

// 创建职位
exports.createJob = async (req, res) => {
  try {
    const { title, industry, location, salaryRange, experience, education, description, requirements, benefits } = req.body;
    const companyId = req.user.id; // 从认证中间件获取企业ID

    // 获取当前用户的公司
    const company = await Company.findOne({
      where: { userId: req.user.id }
    });

    if (!company) {
      return res.status(400).json({ message: '请先创建公司信息' });
    }

    const job = await Job.create({
      title,
      industry,
      location,
      salaryRange,
      experience,
      education,
      description,
      requirements,
      benefits,
      companyId: company.id
    });

    res.status(201).json({
      success: true,
      message: '职位创建成功',
      data: job
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建职位失败',
      error: error.message
    });
  }
};

// 更新职位
exports.updateJob = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, industry, location, salaryRange, experience, education, description, requirements, benefits, status } = req.body;
    const companyId = req.user.id;

    // 查找职位并验证所有权
    const job = await Job.findByPk(id, {
      include: [{ model: Company, attributes: ['id', 'name', 'industry', 'logo'] }]
    });
    if (!job) {
      return res.status(404).json({
        success: false,
        message: '职位不存在'
      });
    }

    // 验证是否为职位创建者
    if (job.companyId !== companyId) {
      return res.status(403).json({
        success: false,
        message: '无权修改此职位'
      });
    }

    // 更新职位信息
    await job.update({
      title, industry, location, salaryRange, experience, education, description, requirements, benefits, status
    });

    res.status(200).json({
      success: true,
      message: '职位更新成功',
      data: job
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新职位失败',
      error: error.message
    });
  }
};

// 删除职位
exports.deleteJob = async (req, res) => {
  try {
    const { id } = req.params;
    const companyId = req.user.id;

    const job = await Job.findByPk(id);
    if (!job) {
      return res.status(404).json({
        success: false,
        message: '职位不存在'
      });
    }

    if (job.companyId !== companyId) {
      return res.status(403).json({
        success: false,
        message: '无权删除此职位'
      });
    }

    await job.destroy();

    res.status(200).json({
      success: true,
      message: '职位删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除职位失败',
      error: error.message
    });
  }
};

// 获取企业发布的所有职位
exports.getCompanyJobs = async (req, res) => {
  try {
    const companyId = req.user.id;
    const jobs = await Job.findAll({
      where: { companyId },
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      success: true,
      data: jobs
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取企业职位列表失败',
      error: error.message
    });
  }
};